package com.winit.openapi.mms.controller;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.spi.context.CommandContext;
import com.winit.mms.spi.v2.item.ItemService;
import com.winit.mms.spi.v2.item.command.PageItemsForOpenApiCommand;
import com.winit.mms.spi.v2.item.vo.PageItemForOpenApiVo;
import com.winit.mms.spi.v2.item.vo.PageVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;

/**
 * 商品Controller，通过开发者平台开放出去的使用winit前缀
 * 
 * @author jiahua.feng
 */
@Controller 
@RequestMapping(value = "/winit/mms/item")
public class WinitItemController extends BaseController {

    /**
     * 商品服务
     */
    @Resource
    private ItemService        itemService;

    /**
     * ums客户信息
     */
    @Resource
    private UmsCustomerService umsCustomerService;

    /**
     * 
     * openapi 接口开发给客户查询商品
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        JSONObject requestJson =  JSON.parseObject(requestMsg.getData().toString());
        PageItemsForOpenApiCommand command = new PageItemsForOpenApiCommand();
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand queryCompanylCommand = new QueryCompanylCommand();
        queryCompanylCommand.setEmail(command.getCtx().getUsername());
        CustomerInfoVO customerInfoVO = umsCustomerService.queryCompanyByUserName(queryCompanylCommand);
        if (customerInfoVO == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        command.setCustomerCode(customerInfoVO.getCode());
        command.setSkuCode(requestJson.getString("skuCode"));
        PageVo pageVo = new PageVo();
        pageVo.setPageNo(requestJson.getInteger("pageNo"));
        pageVo.setPageSize(requestJson.getInteger("pageSize"));
        command.setPageVo(pageVo);
        Page<PageItemForOpenApiVo> page = itemService.pageItemsForOpenApi(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
}
